package AndEngineTest.java;

import java.util.Random;

import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

public class PhergFace extends AnimatedSprite {

	private PhysicsWorld mPhysicsWorld;
	private Vector2 mVelocity = new Vector2(0, 0);
	private Vector2 mClickAnchorCenterOffset = new Vector2(0, 0);
	private Body mBody;
	
	private static final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
	
	public PhergFace(float pX, float pY, TiledTextureRegion pTiledTextureRegion, PhysicsWorld pPhysicsWorld)
	{
		super(pX, pY, pTiledTextureRegion);
		mPhysicsWorld = pPhysicsWorld;
		
		mBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, this, BodyType.DynamicBody, FIXTURE_DEF);
      
		// random wink time so all faces dont blink together
		final Random generator = new Random();
		final int iNextNum = generator.nextInt(10);
		this.animate(100 + (iNextNum * 300));		
	}
	
	@Override
	public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY)
	{
		float physicsSpaceX = ((pTouchAreaLocalX - mClickAnchorCenterOffset.x) + this.mX) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
		float physicsSpaceY = ((pTouchAreaLocalY - mClickAnchorCenterOffset.y) + this.mY) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
		// touched down on this beast.  Set vel to 0.  Set position
		if (pSceneTouchEvent.isActionDown())
		{
			mClickAnchorCenterOffset = new Vector2(pTouchAreaLocalX - mWidth * 0.5f, pTouchAreaLocalY - mHeight * 0.5f);
			mBody.setLinearVelocity(new Vector2(0, 0));
		}
		else if (pSceneTouchEvent.isActionMove())
		{
			mVelocity = new Vector2(physicsSpaceX - mBody.getPosition().x, physicsSpaceY - mBody.getPosition().y);
			mBody.setTransform(new Vector2(physicsSpaceX, physicsSpaceY), mBody.getAngle());
			return true;
		}
		// UNLEASH THE BEAST! Apply linear vel.
		else if(pSceneTouchEvent.isActionUp())
		{
			mBody.setLinearVelocity(mVelocity.mul(10));
			return true;
		}
		return false;
	}
	
	public Body getBody()
	{
		return mBody;
	}

}
